package com.binyouwei.udp_lib;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class MulticastReceiver {

    public static void main(String[] args) {
        try {
            // 同发送者使用的组播地址
            InetAddress group = InetAddress.getByName("239.0.0.1");
            // 同发送者使用的端口
            int port = 4446;
            
            // 创建MulticastSocket并绑定到指定端口
            MulticastSocket socket = new MulticastSocket(port);
            
            // 加入组播组
            socket.joinGroup(group);
            
            System.out.println("Joined the multicast group. Waiting for messages...");
            
            // 创建用于接收数据的DatagramPacket
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            
            // 接收数据包
            socket.receive(packet);
            
            // 打印接收到的消息
            String received = new String(packet.getData(), 0, packet.getLength());
            System.out.println("Received message: " + received);
            
            // 离开组播组（可选）
            // socket.leaveGroup(group);
            
            // 关闭socket
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
